// pages/album/album_detail/album_detail.js
import { getAlbumPictures, createAlbumPicture, delAlbumPicture, updateAlbum, deleteAlbum } from '../../../api/album'
import { isEmpty } from '../../../utils/validator'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    moveIcon: app.globalData.moveIcon,
    imgList: [],
    pictures: [],
    result: {},
    album: {},
    query: {
      album_name: '',
      page: 1,
      page_size: 30
    },
    delOperate: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      [`query.album_name`]: options.name,
      album: options
    })
    wx.setNavigationBarTitle({
      title: options.name,
    })
    wx.showLoading({ title: '加载中', mask: true })
    this._fetchData(this.data.query).then(res => {
    }).finally(() => wx.hideLoading())
  },
  /**
   * 获取数据
   * @param {*} query 
   */
  _fetchData: function (query) {
    return getAlbumPictures(query).then(res => {
      const pictures = res.data.results
      let imgList = pictures.map(picture => picture.image)
      this.setData({
        result: res.data,  // 记录分页等查询信息
        pictures: this.data.pictures.concat(pictures),
        imgList: this.data.imgList.concat(imgList)
      })
      return pictures
    }).catch(() => {
      return []
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  // 修改相册名称
  albumNameBlur(e) {
    this.setData({
      new_album_name: e.detail.value
    })
  },
  // 确认修改
  modifyAlbumTap() {
    let { new_album_name } = this.data
    if (isEmpty(new_album_name)) {
      return toptip.show('相册名称不能为空')
    }
    updateAlbum(this.data.album.id, { 'name': new_album_name }).then(res => {
      // toptip.show('创建成功', { type: 'success' })
      wx.setNavigationBarTitle({
        title: new_album_name,
      })
      this.setData({
        [`album.name`]: new_album_name,
        ['query.album_name']: new_album_name,
        modalName: null,
        new_album_name: ''
      })
      return

    }).catch((res) => {
      return toptip.show(res.data.msg.name[0])
    })
  },
  // 删除相册
  deleteAlbumTap() {
    deleteAlbum(this.data.album.id).then(res => {
      wx.reLaunch({
        url: '../album',
      })
    })
  },
  ChooseImage() {
    var that = this
    wx.chooseImage({
      // count: , //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        createAlbumPicture(res.tempFilePaths, that.data.query.album_name).then(imgs => {
          let pictures = imgs.map(picture => JSON.parse(picture.data).data)//  格式化上传成功的
          let imgList = pictures.map(picture => picture.image) // 用于显示
          this.setData({
            pictures: pictures.concat(this.data.pictures),
            imgList: imgList.concat(this.data.imgList)
          })
          wx.showToast({ title: '上传成功', mask: true })
        }).catch(() => wx.hideLoading())
      }
    });
  },
  ViewImage(e) {
    console.log(e)
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '主人',
      content: '确定要删除这段回忆吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          // splice 删除index元素
          delAlbumPicture(e.currentTarget.dataset.id).then(res => {
            this.data.imgList.splice(e.currentTarget.dataset.index, 1)
            this.data.pictures.splice(e.currentTarget.dataset.index, 1)
            this.setData({
              imgList: this.data.imgList,
              pictures: this.data.pictures
            })
          })
        }
      }
    })
  },
  delOperationTap(e) {
    const that = this
    this.setData({
      delOperate: !that.data.delOperate
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let { query, result } = this.data
    if (result.has_next) {
      query['page'] = result.next
      this.setData({ loadMoreStatus: 'loading' })
      this._fetchData(query).then(res => {
        this.setData({ loadMoreStatus: 'nomore' })
      }).catch(() => this.setData({ loadMoreStatus: 'hidding' }))
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})